//
//  ZJLoginViewController.m
//  zijinli®an
//
//  Created by lzy on 2017/3/7.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "ZJLoginViewController.h"
#import "LogView.h"
#import "ZJNavTool.h"
#import "ZJRegisterViewController.h"
#import "ZJFindPswViewController.h"
#import "ZJMineViewController.h"
#import "ZJBaseNavControllerViewController.h"
#import "FindWordViewController.h"
#import "NewRegistViewController.h"
#import "AppDelegate.h"



@interface ZJLoginViewController ()<UITextFieldDelegate,LogViewDelegate,WXApiDelegate,TencentSessionDelegate,QQShareDelegate>
//导航view
{
    AppDelegate *appdelegate;
    TencentOAuth *_tencentOAuth;
    NSMutableArray *_permissionArray;   //权限列表
}

@property (nonatomic ,strong) NSString *uuid;
@end

@implementation ZJLoginViewController
    static  NSInteger const QQ_LOGIN_TAG=101;
    static NSInteger const WE_CHAT_LOGIN_TAG=102;

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //创建
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    // 读取账户
    NSString * name = [userDefaults objectForKey:@"userNameabc"];
    //读取密码
    NSString * password = [userDefaults objectForKey:@"passwordabc"];
    if (password!=nil) {
        self.LogV.IDTF.text=password;
        self.LogV.pswTF.text=name;
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"passwordabc"];
        UITextField *_field = (UITextField *)self.LogV.IDTF;
        NSString *str=_field.text;
        [self.LogV.logBtn setBackgroundColor:[str isEqualToString:@""]?button_gray_Color:button_Red_Color];
        [self.LogV.logBtn setTitleColor:[str isEqualToString:@""]?Btn_TxTGray_Color:[UIColor whiteColor] forState:UIControlStateNormal];
    }
   
}
-(void)createView{
    
    [self initTitle:MyString(@"登录")];
    
    
    appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.qqDelegate=self;
    //self.uuid=[[NSUUID UUID] UUIDString];
    [ZJNavTool rightItemOnNavigationItem:self target:self action:@selector(registerClick:) andType:item_register];
    _LogV=[[LogView alloc]init];
    _LogV.frame=CGRectMake(0, 0, MainW, MainH);
    NSString* avatar=[ZJUserDefaultsTools getAvatar];
    if (!_modality) {
        UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                           initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                           target:nil action:nil];
        negativeSpacer.width = -10;
        //左边返回按钮
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake(0, 0, 12, 18);
        [backBtn setBackgroundImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
        self.navigationItem.leftBarButtonItem=leftItem;
        self.hidesBottomBarWhenPushed=YES;
    }
    
    if (avatar!=nil) {
        [self.LogV.headView sd_setImageWithURL:[NSURL URLWithString:[ZJUserDefaultsTools getAvatar]]];

    }else{
        self.LogV.headView.image=[UIImage imageNamed:@"img_head_nor"];
    }
    [self.view addSubview:self.LogV];
    if ([WXApi isWXAppInstalled]) {
        NSLog(@"该用户手机安装了微信");
        _LogV.weiChatBtn.hidden = NO;
    }  else{
        NSLog(@"该用户手机未安装微信");
        _LogV.weiChatBtn.hidden =YES;
    }
 
}
-(void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)doOpeartion{
    _LogV.delegete=self;
    _LogV.IDTF.delegate=self;
    _LogV.pswTF.delegate=self;
    [_LogV.qqBtn addTarget:self action:@selector(thridLogin:) forControlEvents:UIControlEventTouchUpInside];
    [_LogV.weiChatBtn addTarget:self action:@selector(thridLogin:) forControlEvents:UIControlEventTouchUpInside];
    [_LogV.CheckBtn addTarget:self action:@selector(CheckBtn) forControlEvents:UIControlEventTouchUpInside];
    _LogV.qqBtn.tag=QQ_LOGIN_TAG;
    [_LogV.qqBtn addTarget:self action:@selector(thridLogin:) forControlEvents:UIControlEventTouchUpInside];
    _LogV.weiChatBtn.tag=WE_CHAT_LOGIN_TAG;
    [_LogV.IDTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_LogV.pswTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.LogV.findpswBtn addTarget:self action:@selector(find) forControlEvents:UIControlEventTouchUpInside];
    [self.LogV.logBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [self doKeyBoardDown];
}
-(void)CheckBtn{
    int i=arc4random()%100;
    [self.LogV.CheckImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/api/validation/captcha/image?it=%d&&sessionId=%@",baseURL,i,self.uuid]]];
}

- (void) textDidChange:(id) sender {
    UITextField *_field = (UITextField *)sender;
    NSString *str=_field.text;
    [self.LogV.logBtn setBackgroundColor:[str isEqualToString:@""]?button_gray_Color:button_Red_Color];
    [self.LogV.logBtn setTitleColor:[str isEqualToString:@""]?Btn_TxTGray_Color:[UIColor whiteColor] forState:UIControlStateNormal];
}




    
-(void) thridLogin:(UIButton*)btn{
        
    switch (btn.tag) {
        case QQ_LOGIN_TAG://qq登录
        {
            [_tencentOAuth getUserInfo];
            _tencentOAuth=[[TencentOAuth alloc]initWithAppId:QQAPPID andDelegate:self];
            
            //设置权限数据 ， 具体的权限名，在sdkdef.h 文件中查看。
            _permissionArray = [NSMutableArray arrayWithObjects: kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_ADD_SHARE,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,nil];
            
            //登录操作
            [_tencentOAuth authorize:_permissionArray inSafari:NO];
            NSLog(@"QQ登录");
        }
        
        break;
        case WE_CHAT_LOGIN_TAG://微信登录
        
        {
            if ([WXApi isWXAppInstalled ]) {
                //构造SendAuthReq结构体
                SendAuthReq* req =[[SendAuthReq alloc ] init]  ;
                req.scope = @"snsapi_userinfo" ;
                req.state = @"WMYWX";
                [WXApi sendAuthReq:req viewController:self delegate:self];
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginClick) name:@"login_Success" object:nil];
            }
            else{
                [MBProgressHUD showError:@"未安装微信"];
            }

            NSLog(@"微信登录");
        }
        default:
        break;
    }


}

- (void)tencentFailedUpdate:(UpdateFailType)reason{
    
    switch (reason)
    {
        case kUpdateFailNetwork:
        {
            //            _labelTitle.text=@"增量授权失败，无网络连接，请设置网络";
            NSLog(@"增量授权失败，无网络连接，请设置网络");
            break;
        }
        case kUpdateFailUserCancel:
        {
            //            _labelTitle.text=@"增量授权失败，用户取消授权";
            NSLog(@"增量授权失败，用户取消授权");
            break;
        }
        case kUpdateFailUnknown:
        default:
        {
            NSLog(@"增量授权失败，未知错误");
            break;
        }
    }
    
    
}
- (void)tencentDidLogin{
    
    /** Access Token凭证，用于后续访问各开放接口 */
    if (_tencentOAuth.accessToken) {
        
        //NSLog(@"accessToken %@ appId:%@   %@",_tencentOAuth.accessToken,_tencentOAuth.openId,_tencentOAuth);
        //获取用户信息。 调用这个方法后，qq的sdk会自动调用
        //- (void)getUserInfoResponse:(APIResponse*) response
        //这个方法就是 用户信息的回调方法。
        [[NSUserDefaults standardUserDefaults]setObject:_tencentOAuth.accessToken forKey:@"QQopenKey"];
        [[NSUserDefaults standardUserDefaults]setObject:_tencentOAuth.openId forKey:@"QQopenid"];
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        dic[@"openKey"]=_tencentOAuth.accessToken;
        dic[@"openId"]=_tencentOAuth.openId;
        NSLog(@" 腾讯的openID:%@",_tencentOAuth.openId);
        dic[@"lang"]=@"zhcn";
        dic[@"pf"]=@"openmobile_ios";
        NSString *wxUrl=[NSString stringWithFormat:@"%@%@",baseURL,API_QQLOGIN];
        AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:wxUrl parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            if ([json[@"status"] intValue] ==142) {
                FindWordViewController *vc=[[FindWordViewController alloc]init];
                vc.type=4;
                vc.logintype=1;
                [self.navigationController pushViewController:vc animated:YES];
            }else if ([json[@"status"] intValue] ==143){
                [self showToast:@"此账号已经绑定"];
            }else if([json[@"status"] intValue] ==141)
            {
            }
            else{
                NSLog(@"你是不是傻b%@",json[@"status"]);
                [ZJUserDefaultsTools saveUserInfoLocal:json];
                [[EMClient sharedClient] loginWithUsername:[ZJUserDefaultsTools getCurrentIMName]
                                                  password:[ZJUserDefaultsTools getCurrentIMPASSWORD]
                                                completion:^(NSString *aUsername, EMError *aError) {
                                                    if (!aError) {
                                                        NSLog(@"登录成功");
                                                        EMPushOptions *emoptions = [[EMClient sharedClient] pushOptions];
                                                        //设置有消息过来时的显示方式:1.显示收到一条消息 2.显示具体消息内
                                                        [[EMClient sharedClient].options setIsAutoLogin:YES];
                                                        //自己可以测试下
                                                        emoptions.displayStyle = EMPushDisplayStyleSimpleBanner;
                                                        [[EMClient sharedClient] updatePushOptionsToServer];
                                                    } else {
                                                        NSLog(@"登录失败");
                                                    }
                                                }];
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            //NSLog(@"请求成功：%@",json);
            //3. 获得网络数据赋值给ExpressInfo对象
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"请求失败：%@",error.description);
        }];
    }else{
        
        NSLog(@"accessToken 没有获取成功");
    }
    
}
- (void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled) {
        NSLog(@" 用户点击取消按键,主动退出登录");
    }else{
        NSLog(@"其他原因， 导致登录失败");
    }
}
-(void)WeChatLogin:(NSDictionary *)Dictionary{
    if ([Dictionary[@"status"] intValue]==142) {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        FindWordViewController *vc=[[FindWordViewController alloc]init];
        vc.type=4;
        vc.logintype=2;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([Dictionary[@"status"] intValue]==143){
        [self showToast:MyString(@"该手机号已被绑定")];
    }else{
        [ZJUserDefaultsTools saveUserInfoLocal:Dictionary];
        [[EMClient sharedClient] loginWithUsername:[ZJUserDefaultsTools getCurrentIMName]
                                          password:[ZJUserDefaultsTools getCurrentIMPASSWORD]
                                        completion:^(NSString *aUsername, EMError *aError) {
                                            if (!aError) {
                                                NSLog(@"登录成功");
                                                EMPushOptions *emoptions = [[EMClient sharedClient] pushOptions];
                                                //设置有消息过来时的显示方式:1.显示收到一条消息 2.显示具体消息内
                                                [[EMClient sharedClient].options setIsAutoLogin:YES];
                                                //自己可以测试下
                                                emoptions.displayStyle = EMPushDisplayStyleSimpleBanner;
                                                [[EMClient sharedClient] updatePushOptionsToServer];
                                            } else {
                                                NSLog(@"登录失败");
                                            }
                                        }];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    NSLog(@"微信登录 %@",Dictionary);
}
-(void)loginClick{
    
    NSLog(@"微信登录成功");
    
}

-(void)eyeAndOpen:(BOOL)isopen
{
    
     self.LogV.pswTF.secureTextEntry=!self.LogV.pswTF.secureTextEntry;
//    if (isopen) {
//        <#statements#>
//    }
}
#pragma -----------------登陆。按钮 方法
-(void)login
{
    if (self.LogV.IDTF.text.length==0) {
        [self showMessage:MyString(@"请输入手机号码")];
        return;
    }
    if (self.LogV.pswTF.text.length==0) {
        [self showMessage:MyString(@"请输入密码")];
        return;
    }
    [self showDialog];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:self.LogV.IDTF.text forKey:@"phone"];
    [parametersDic setObject:self.LogV.pswTF.text forKey:@"password"];
    [parametersDic setObject:self.LogV.CheckNum.text forKey:@"imageCode"];
    //[parametersDic setObject:self.uuid forKey:@"imei"];
    
    [[ZJBaseAFManager sharedManager] POST:API_LOGIN parameters:parametersDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject[@"msg"]);
        [self dismissDialog];
        if ([responseObject[@"status"] integerValue]==133) {
            LXAlertView*alertView=[[LXAlertView alloc]initWithTitle:@"" message:MyString(@"密码错误") cancelBtnTitle:MyString(@"确定") otherBtnTitle:MyString(@"忘记密码") clickIndexBlock:^(NSInteger clickIndex) {
                if (clickIndex==0) {
                    [self getCheckNUm];
                }else{
                    ZJFindPswViewController *findVC=[[ZJFindPswViewController alloc]init];
                    [self.navigationController pushViewController:findVC animated:YES];
                }
               
            }];
            [alertView showLXAlertView];
        }else if ([responseObject[@"status"] integerValue]==132){
            self.uuid=responseObject[@"sessionId"];
            [self showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
            [self getCheckNUm];
            NSNotification * notice = [NSNotification notificationWithName:@"123" object:nil userInfo:nil];
                    //发送消息
            [[NSNotificationCenter defaultCenter]postNotification:notice];
        }else if ([responseObject[@"status"] integerValue]==0){
            NSLog(@"登录信息:%@",responseObject);
            [ZJUserDefaultsTools saveUserInfoLocal:responseObject];
            [[EMClient sharedClient] loginWithUsername:[ZJUserDefaultsTools getCurrentIMName]
                                              password:[ZJUserDefaultsTools getCurrentIMPASSWORD]
                                            completion:^(NSString *aUsername, EMError *aError) {
                                                if (!aError) {
                                                    NSLog(@"登录成功");
                                                    EMPushOptions *emoptions = [[EMClient sharedClient] pushOptions];
                                                    //设置有消息过来时的显示方式:1.显示收到一条消息 2.显示具体消息内容.
                                                    //自己可以测试下
                                                    emoptions.displayStyle = EMPushDisplayStyleSimpleBanner;
                                                    [[EMClient sharedClient] updatePushOptionsToServer];
                                                    if (!aError)
                                                    {
                                                        [[EMClient sharedClient].options setIsAutoLogin:YES];
                                                    }

                                                } else {
                                                    NSLog(@"登录失败");
                                                }
                                            }];
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self dismissDialog];
    }];
    
}

-(void)find
{
    ZJFindPswViewController *findVC=[[ZJFindPswViewController alloc]init];
    [self.navigationController pushViewController:findVC animated:YES];
}



-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
    
}
-(void)getCheckNUm{
    int i=arc4random()%100;
    [self.LogV.CheckImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/api/validation/captcha/image?it=%d&&sessionId=%@",baseURL,i,self.uuid]]];
    //
}


-(void)registerClick:(UIButton *)btn
{
    ZJRegisterViewController *registerVC=[[ZJRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
    
}

@end
